<template>
    <div>
        <div style="height: 600px; display: flex;">
            <vue-search-tree ref="searchTreeRef" style="flex: 1;"
            :nodes="departmentMemberTreeData"
            :setting="setting"
            @onCreated="handleCreated"
            :hasSearch="true"
            treeHeight="calc(100% - 35px)">
                <div slot="search" slot-scope="{ ztreeId }" class="searchPid">
                    <span class="icon"></span>
                    <input type="text" :id="ztreeId + '_search'" v-model="searchKey" placeholder="请输入部门员工/名称"/>
                </div>
            </vue-search-tree>
            <div style="width: 400px">
                <h2>你选择的节点</h2>
                <el-tag
                    v-for="(tag, index) in checkedTags"
                    :key="tag.tagId"
                    closable @close="tagClose(tag,index)">
                    {{tag.tagName}}
                </el-tag>
            </div>
        </div>
        <div>
            <el-button type="primary" @click="resetCheckedTags()">获取勾选的节点</el-button>
        </div>
    </div>
</template>

<script>
    import axios from 'axios';
    import VueSearchTree from '@/components/vue-search-tree/ztree.vue'

    function getContent(pathArray) { // 获取树节点的路径
        // if (pathArray.length === 1) {
        //     return pathArray[0].nodeName;
        // } else if (pathArray.length === 2) {
        //     return pathArray[0].nodeName + '>' + pathArray[1].nodeName;
        // } else if (pathArray.length === 3) {
        //     return pathArray[0].nodeName + '>' + pathArray[1].nodeName + '>' + pathArray[2].nodeName;
        // } else {
        //     return pathArray[0].nodeName + '>' + pathArray[1].nodeName + '>...' + pathArray[pathArray.length -1].nodeName;
        // }
        return pathArray.map(item =>item.nodeName).join('>');
    }

    export default {
        components: {
            VueSearchTree, // 引入组件包
        },
        data() {
            let _this = this;            
            return {
                departmentMemberTreeData: [],
                ztreeObj: null,
                checkedTags: [],
                administrators: [],
                searchKey: '',
                searchCheckedParentNodes: [], // 搜索时点选的父节点
                setting: {
                    check: {
                        enable: true,
                        // chkboxType: {'Y': '', 'N': ''}
                    },
                    data: {
                        // 设置图标库(采用iconfont class形式)
                        iconMap: {
                            0: 'iconfilter-fill',
                            1: 'iconhome',
                            2: 'iconstar'
                        },
                        // 设置对应每个节点的节点类型，与数据中customType对应(25行)
                        key: {
                            nodeType: 'customType',
                            name: 'nodeName',
                            title: 'nodeName',
                            children: 'children',
                            isParent: 'hasChild'
                        }
                    },
                    callback: {
                        onCheck: function (event, treeId, treeNode) {
                            let node = treeNode;
                            if (_this.searchKey) { // 如果是搜索状态
                                let { checked, half } = node.getCheckStatus();
                                if (node.hasChild) { // 如果是父节点
                                    if (checked && !half) {
                                        _this.searchCheckedParentNodes.push(node);
                                    }
                                }
                            }
                            if (node.checked) { // 如果是选中状态
                                let pathNodes = node.getPath();
                                for (let i = 0; i <= pathNodes.length - 1; i++) {
                                    let pNode = pathNodes[i];
                                    let { checked, half } = pNode.getCheckStatus();
                                    let content = getContent(pNode.getPath());
                                    if (checked && !half) {
                                        // TODO: 从 checkedTags中删除这个节点下面已经选中的子节点
                                        let deptCheckedTags = _this.checkedTags.filter(item => item.tagFrom === 'departmentMemberTree');                                        
                                        if (deptCheckedTags.length) {
                                            let delTags = []
                                            deptCheckedTags.forEach(d => {
                                                let subNode = _this.ztreeObj.getNodeByParam('nodeId', d.tagId);
                                                // let dPNodes = subNode.getPath();
                                                let dPNodes = [];
                                                let parentNode = _this.ztreeObj.getNodeByParam('id', d.parentId);
                                                while(parentNode) {
                                                    dPNodes.unshift(parentNode);
                                                    parentNode = _this.ztreeObj.getNodeByParam('id', parentNode.parentId);
                                                }
                                                let f = dPNodes.find(x => x.nodeId === pNode.nodeId);
                                                if (f) {
                                                    delTags.push(d);
                                                }
                                            });
                                            if (delTags.length) {
                                                delTags.forEach(d => {
                                                    let dIndex = _this.checkedTags.findIndex(tag => tag.tagId === d.tagId);
                                                    if (dIndex > -1) {
                                                        _this.checkedTags.splice(dIndex, 1);
                                                    }
                                                })
                                            }
                                        }
                                        let obj = {
                                            tagName: pNode.nodeName,
                                            parentId: pNode.parentId,
                                            tagId: pNode.nodeId,
                                            class: "normal",
                                            content: content,
                                            // content: node.nodeName,
                                            tagFrom: "departmentMemberTree",
                                            tagType: pNode.nodeType
                                        };
                                        _this.checkedTags.push(obj);
                                        break;
                                    }
                                }
                            } else { // 如果是取消选中状态
                                let findIndex = _this.checkedTags.findIndex(item => item.tagId === node.nodeId);
                                if (findIndex > -1) {
                                    _this.checkedTags.splice(findIndex, 1);
                                }
                                // let pathNodes = node.getPath(); // getPath()只能取到被选中节点的所有父节点的数据集合
                                let parentNode = node.getParentNode()
                                if (!parentNode) return;
                                let pathNodes1 = [];
                                while(parentNode) {
                                    pathNodes1.unshift(parentNode);
                                    parentNode = parentNode.getParentNode()
                                }
                                if (!pathNodes1) return;
                                console.log(pathNodes1, 'yyyyyyyyyy');
                                if (pathNodes1.length === 0) { // 点击的是根节点
                                    // _this.checkedTags = [];
                                    let postCheckedTags = _this.checkedTags.filter(item => item.tagFrom !== 'departmentMemberTree');
                                    _this.checkedTags = postCheckedTags;
                                }
                                for (let i = pathNodes1.length -1; i >= 0; i--) {
                                    let pNode = pathNodes1[i];
                                    let children = pNode.children;
                                    let checkedChildren = [];
                                    let hidedChildren = []; // 被隐藏起来的节点和被禁用掉的节点
                                    for(let m = 0; m < children.length; m++) {
                                        let nItem = children[m];
                                        let nStatus = nItem.getCheckStatus(); // 搜索时被隐藏起来的节点是获取不到状态值的，所以可以用continue跳过
                                        if (!nStatus) { 
                                            hidedChildren.push(nItem);
                                            continue;
                                        }
                                        let { checked, half } = nStatus;
                                        if (checked && !half) checkedChildren.push(nItem);
                                    }
                                    if (checkedChildren.length + hidedChildren.length === children.length -1) { // 说明原来这个父节点是全选状态                                        
                                        let pNodeIndex = _this.checkedTags.findIndex(item => item.tagId === pNode.nodeId); // 从checkedTags中删除这个父节点
                                        if (pNodeIndex > -1) {
                                            _this.checkedTags.splice(pNodeIndex, 1);
                                        }
                                        for (let j = 0; j <= children.length -1; j++) {
                                            let child = children[j];
                                            let status = child.getCheckStatus()
                                            if (!status) continue; // 如果没有status，应该是一个被禁用的节点，直接跳过
                                            if (!child.checked || status.half) continue; // 子节点刚好是这个取消选中的节点，则直接跳过
                                            let content = getContent(child.getPath());
                                            let obj = {
                                                tagName: child.nodeName,
                                                parentId: child.parentId,
                                                tagId: child.nodeId,
                                                class: "normal",
                                                content: content,
                                                // content: node.nodeName,
                                                tagFrom: "departmentMemberTree",
                                                tagType: child.nodeType
                                            };    
                                            _this.checkedTags.push(obj);
                                        }
                                    }
                                }
                            }
                        }
                    },
                    view: {
                        // 开启图标显示功能
                        showIcon: true
                    },
                }
            };
        },
        mounted() {
            this.firstData();
        },
        methods: {
            firstData() {
                // let url= `http://172.31.119.38:35002/roc/accessweb/web/org/getAllTree?appId=945`
                let url= `searchTree.json`
                axios.get(url, {
                    headers: {
                    'X-Access-Source': 'roc',
                    'X-Access-Token': '6bae445346b531f2b2fd565c321127d6'
                    }
                }).then(res => {
                    if (res.data.code === '0') {
                        let data = res.data.data;
                        let _this = this;
                        function fn(pArray) {
                            pArray.forEach(pData => {
                                let find = _this.administrators.find(a => a.memberId === pData.nodeId);
                                if (find) {
                                    pData.nodeName = pData.nodeName + ' (应用管理员)';
                                    pData.checked = true;
                                    pData.chkDisabled = true;
                                    pData.isAdmin = true;
                                }
                                if (pData.nodeType === 0 && pData.parentId === "d_0") {
                                    // 集团
                                    pData.hasChild = true;
                                    pData.customType = 0; // 这个属性是用来设置图标的
                                    fn(pData.children);
                                } else if (pData.nodeType === 0 && pData.parentId !== "d_0") {
                                    // 专业部门
                                    pData.hasChild = true;
                                    pData.customType = 1;
                                    fn(pData.children);
                                } else if (pData.nodeType === 1) {
                                    // 部门人员
                                    pData.hasChild = false;
                                    pData.customType = 2;
                                    delete pData["children"];
                                }
                            });
                        }
                        fn(data);
                        this.departmentMemberTreeData = data;
                    }
                })
            },
            handleCreated: function(ztreeObj) {
                this.ztreeObj = ztreeObj;
                // onCreated 中操作ztreeObj对象展开第一个节点
                ztreeObj.expandNode(ztreeObj.getNodes()[0], true);
            },
            tagClose(tag) {
                let index = this.checkedTags.findIndex(item => item.tagId === tag.tagId);
                this.checkedTags.splice(index, 1);
                // 同步到树节点
                let { tagId, tagFrom } = tag;
                if (tagFrom === 'departmentMemberTree') {
                    let node = this.ztreeObj.getNodeByParam("nodeId", tagId, null);
                    if (node) {
                        this.ztreeObj.checkNode(node, false, true);
                    }
                } else {
                    // let node = this.$refs[tagFrom].store.nodesMap[tagId];
                    // node.checked = false;
                }
            },
            getCheckedNodes() {
                let allCheckedNodes = this.ztreeObj.getCheckedNodes();
                let checkedNodes = allCheckedNodes.filter(item => {
                    let { checked, half } = item.getCheckStatus();
                    if (checked && !half) return true;
                    else return false;
                });
            },
            resetCheckedTags() {
                if (this.searchCheckedParentNodes.length) {
                    this.searchCheckedParentNodes.forEach(node => {
                        this.ztreeObj.checkNode(node, true, true);
                    })
                }
                let allCheckedNodes = this.ztreeObj.getCheckedNodes();
                let checkedNodes = allCheckedNodes.filter(item => {
                    let { checked, half } = item.getCheckStatus();
                    if (checked && !half) return true;
                    else return false;
                });
                console.log(checkedNodes)
                let checkedParents = [];
                checkedNodes.forEach(node => {
                    if (node.hasChild) { // 如果不是叶子节点
                        let p = node.getParentNode();                                
                        let content = getContent(node.getPath());
                        let obj = {
                            tagName: node.nodeName,
                            parentId: node.parentId,
                            tagId: node.nodeId,
                            class: "normal",
                            content: content,
                            tagFrom: "departmentMemberTree",
                            tagType: node.nodeType
                        };
                        if (!p) { // 如果这个节点没有父节点
                            checkedParents.push(obj);
                        } else {
                            let half = p.getCheckStatus().half;
                            if (half) { // 如果这个不是叶子节点的父节点是半选中状态
                                checkedParents.push(obj);
                            }
                        }                        
                    } else { // 如果是叶子节点
                        let p = node.getParentNode();
                        let half = p.getCheckStatus().half;
                        if (half) { // 如果叶子节点的父节点是半选中状态
                            let content = getContent(node.getPath());
                            let obj = {
                                tagName: node.nodeName,
                                parentId: node.parentId,
                                tagId: node.nodeId,
                                class: "normal",
                                content: content,
                                tagFrom: "departmentMemberTree",
                                tagType: node.nodeType
                            };
                            checkedParents.push(obj)
                        }
                    }
                });
                console.log(checkedParents, 'bbbb');
                let postCheckedTags = this.checkedTags.filter(item => item.tagFrom !== 'departmentMemberTree');
                this.checkedTags = [...checkedParents,...postCheckedTags];
            }
        },
        watch: {
            searchKey(newV, oldV) {
                if (!newV) { // 如果变空了
                    setTimeout(() => {
                        this.resetCheckedTags();
                        this.searchCheckedParentNodes = [];
                    }, 1000)
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
.searchPid {
    width: 210px;
    height: 30px;
    border: 1px solid #E8EAEB;
    padding-top: 2px;
    border-radius: 15px;
}
.searchPid .icon {
    float: left;
    width: 16px;
    height: 16px;
    background: url() no-repeat;
    margin-left: 11px;
    margin-top: 7px;
}
.searchPid input {
    border: none;
    float: left;
    width: 150px;
    height: 30px;
    line-height: 30px;
    margin-left: 8px;
    background: none;
    &:focus {
        outline: none;
    }
}
</style>